var zhibiaoHtml = '';	
var jislHtml = '';
var groupHtml = '';
var zbListData = []

function onOptionChange1(){
	var selectedOption = event.target.selectedOptions[0]
	var xsmc = document.getElementById('xspc')
	if(selectedOption){
		xsmc.value = selectedOption.getAttribute('value') + '('+selectedOption.getAttribute('code')+')'
	} else {
		xsmc = ""
	}
	var groupOptions = ''
	var selectedIndex = event.target.selectedIndex
	for(var j=0;j<zbListData[selectedIndex].collist.length;j++){
		groupOptions += '<option value="'+zbListData[selectedIndex].collist[j].COLNAME+'" code="'+zbListData[selectedIndex].collist[j].COLBM+'" colType="'+zbListData[selectedIndex].collist[j].COLTYPE+'">'+zbListData[selectedIndex].collist[j].COLNAME+'</option>'
	}
	document.getElementById('zb_select_2').innerHTML = groupOptions
}
function setjislHtml(node){
	function getSubNodes(nodes){
		var arr = []
		for(var i=0;i<nodes.length;i++){
			var node = nodes[i]
			arr.push(node.name)
			if(node.children && node.children.length > 0){
				arr = arr.concat(getSubNodes(node.children))
			}
		}
		return arr;
	}

	var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	var nodes = treeObj.getNodes();
	var nameArr = getSubNodes(nodes[0].children)

	var isCalc = node.hasOwnProperty('tjfw')
	console.log('node')
	var name = isCalc ? node.name : ''
	var express = isCalc ? node.express : ''
	var display = isCalc ? node.display : ''
	var tjfw = isCalc ? node.tjfw : ''
	
	var html = ''
	for(var i=0;i<nameArr.length;i++){
		html += '<li>'+(i+1)+'.'+nameArr[i]+'</li>'
	}
	jislHtml = '';
	jislHtml+='<div class="info-box">'
		+'<div class="left-list fl" style="width:150px">'
		+'<ul>'
		+html
		+'</ul></div>'
		+'<div class="right-list fl ml10">'
			+'<ul>'
			+'<li>'
			+'<span class="left-title">显示名称</span>'
			+'<span class="right-info"><input type="text" id="ggxspc" value="'+name+'"class="layui-text"></span>'
			+'</li>'
			+'<li>'
			+'<span class="left-title">计算表达式</span>'
			+'<span class="right-info"><textarea id="ggjsbdas" value="'+express+'" type="text" class="layui-area">'+express+'</textarea></span>'
			+'</li>'
			+'<li>'
			+'<span class="left-title">统计范围</span>'
			+'<span class="right-info"><textarea id="ggtjfw" value="'+tjfw+'" type="text" class="layui-area">'+tjfw+'</textarea></span>'
			+'</li>'
			+'<li>'
			+'<span class="left-title">是否显示</span>'
				+'<span class="right-info"><select id="ggifshow" class="selects"><option value="是" '+(display == '是' ? 'selected="selected"' : '')+'>是</option><option value="否" '+(display == '否' ? 'selected="selected"' : '')+'>否</option></select></span>'
			+'</li>'
			+'</ul>'
		+'</div>'
		+'</div>';
}

function setzhibiaoHtml(data1,data2,data,node){
	var zbOoptions = null;
	var selectName = null;
	console.log(data)
	for(var i=0;i<data.length;i++){
		if(!selectName && node && node.name.indexOf(data[i].NAME) >= 0){
			selectName = node.name
			zbOoptions += '<option selected="selected" rnum="'+data[i].rnum+'" value="'+data[i].NAME+'" code="'+data[i].ZBDM+'">'+data[i].NAME+'</option>'
		} else {
			zbOoptions += '<option rnum="'+data[i].rnum+'"value="'+data[i].NAME+'" code="'+data[i].ZBDM+'">'+data[i].NAME+'</option>'
		}
	}
	
	var groupOptions = ""
	for(var j=0;j<data[0].collist.length;j++){
		groupOptions += '<option value="'+data[0].collist[j].COLNAME+'" code="'+data[0].collist[j].COLBM+'" colType="'+data[0].collist[j].COLTYPE+'">'+data[0].collist[j].COLNAME+'</option>'
	}
	deValue = selectName || (data[0].NAME+'('+data[0].ZBDM+')')
	zhibiaoHtml = '';
	console.log(node)
	var starttime = node ? node.starttime : 0
	var endtime = node ? node.endtime : 0
	
	var starttimeOptions = ''
	var endtimeOptions = ''
	var value = ['当前报告期','上期','去年同期']
	for(var i=0;i<value.length;i++){
		starttimeOptions += '<option value="'+value[i]+'" '+(starttime == i ? 'selected="selected"' : '')+'>'+value[i]+'</option>'
		endtimeOptions += '<option value="'+value[i]+'" '+(endtime == i ? 'selected="selected"' : '')+'>'+value[i]+'</option>'
	}

	zhibiaoHtml+='<div class="info-box">'
		+'<ul><li>'
		+'<span class="left-title">指标</span>'
		+'<span class="right-info"><select id="zb_select_1" onchange="onOptionChange1()" class="selects">'
		+zbOoptions
		+'</select></span>'
		+'<span class="left-title ml20">字段</span>'
		+'<span class="right-info"><select id="zb_select_2" class="selects">'
		+groupOptions
		+'</select></span>'
		+'</li>'
		+'<li>'
		+'<span class="left-title">开始时间</span>'
		+'<span class="right-info"><select id="zb_select_3" class="selects">'+starttimeOptions+'</select></span>'
		+'</li>'
		+'<li>'
		+'<span class="left-title">结束时间</span>'
		+'<span class="right-info"><select id="zb_select_4" class="selects">'+endtimeOptions+'</select></span>'
		+'</li>'
		+'<li>'
		+'<span class="left-title">显示名称</span>'
		+'<span class="right-info"><input type="text" id="xspc" value="'+deValue+'"class="layui-text"></span>'
		+'</li>'
		+'<li>'
		+'<span class="left-title">是否显示</span>'
			+'<span class="right-info"><select id="zb_select_5" class="selects"><option value="是">是</option><option value="否">否</option></select></span>'
		+'</li>'
	+'</div>';
}
function onselectChange(){
	console.log(event.target.selectedOptions[0])
	var option = event.target.selectedOptions[0]
	var scheme = option.getAttribute('scheme')
	var schemeLength = scheme.split(',').length
	var li = document.getElementById('showOrHide')
	console.log(scheme)
	if(scheme && scheme != "undefined"){
		if(li){
			li.style.display="list-item"
		}
		var cengshu = ''
		for(var j=0;j<schemeLength;j++){
			cengshu += '<option value="'+'第'+(j+1)+'层'+'">'+'第'+(j+1)+'层'+'</option>'
		}
		var select = document.getElementById('gp_select_2')
		var fenzumg = option.getAttribute('value')
		document.getElementById('gxsmc').value = fenzumg
		if(select){
			select.innerHTML = cengshu
		}
	} else {
		if(li){
			li.style.display="none"
		}
	}
}

function setGroupHtml(data,node,isEdit){
	console.log(rowList)
	console.log(data)
	console.log(node)
	var groupOptions = ''
	var cengshu = '<li style="display:none" id="showOrHide"><span class="left-title">层次</span><span class="right-info"><select id="gp_select_2" class="selects"></select></span></li>'
	var editName = null
	var cs = node ? node.cs : 1;
	var selectIndex = 0;

	if(node.id == 2){
		for(var i=0;i<data.custom.length;i++){
			var item = data.custom[i]
			if(!editName && isEdit){
				if(item.NAME == node.name){
					selectIndex = i
					editName = node.name
				}
				groupOptions += '<option selected="selected" value="'+item.NAME+'" scheme="'+item.SCHEME+'" column="'+item.COLBM+'">'+item.NAME+'</option>'
			} else {
				groupOptions += '<option value="'+item.NAME+'" scheme="'+item.SCHEME+'" column="'+item.COLBM+'">'+item.NAME+'</option>'
			}
		}
		for(var i=0;i<data.normal.length;i++){
			var item = data.normal[i]
			if(!editName && isEdit){
				if(item.NAME == node.name){
					selectIndex = i
					editName = node.name
				}
				groupOptions += '<option selected="selected" value="'+item.NAME+'" scheme="'+item.SCHEME+'" column="'+item.COLBM+'">'+item.NAME+'</option>'
			} else {
				groupOptions += '<option value="'+item.NAME+'" scheme="'+item.SCHEME+'" column="'+item.COLBM+'">'+item.NAME+'</option>'
			}
		}
	}
	else if(node.groupType != 'NORMAL'){
		for(var i=0;i<data.custom.length;i++){
			var item = data.custom[i]
			if(!editName && isEdit){
				if(item.NAME == node.name){
					selectIndex = i
					editName = node.name
				}
				groupOptions += '<option selected="selected" value="'+item.NAME+'" scheme="'+item.SCHEME+'" column="'+item.COLBM+'">'+item.NAME+'</option>'
			} else {
				groupOptions += '<option value="'+item.NAME+'" scheme="'+item.SCHEME+'" column="'+item.COLBM+'">'+item.NAME+'</option>'
			}
		}
	} else {
		for(var i=0;i<data.normal.length;i++){
			var item = data.normal[i]
			if(!editName && isEdit){
				if(item.NAME == node.name){
					selectIndex = i
					editName = node.name
				}
				groupOptions += '<option selected="selected" value="'+item.NAME+'" scheme="'+item.SCHEME+'" column="'+item.COLBM+'">'+item.NAME+'</option>'
			} else {
				groupOptions += '<option value="'+item.NAME+'" scheme="'+item.SCHEME+'" column="'+item.COLBM+'">'+item.NAME+'</option>'
			}
		}
	}
	if(node.groupType == 'NORMAL'){
		var csArr = data.normal[selectIndex].SCHEME.split(',')
		cengshu = '<li><span class="left-title">层次</span><span class="right-info"><select id="gp_select_2" class="selects">'
		for(var j=0;j<csArr.length;j++){
			cengshu += '<option '+(cs == j+1 ? 'selected="selected"' : '')+'value="'+'第'+(j+1)+'层'+'">'+'第'+(j+1)+'层'+'</option>'
		}
		cengshu += '</select></span></li>'
	}
	var fenzumc = editName || data.normal[0].NAME
	groupHtml = "";
	groupHtml += '<div class="info-box">'
			+'<ul><li>'
			+'<span class="left-title">分组</span>'
			+'<span class="right-info"><select onchange="onselectChange()" id="gp_select_1" class="selects">'
			+groupOptions
			+'</select></span></li>'
			+cengshu
			+'<li><span class="left-title">显示名称</span>'
			+'<span class="right-info"><input type="text" id="gxsmc" value="'+fenzumc+'"class="layui-text"></span>'
			+ '</div>'
}

var curDragNodes, newCount = 1;
function dropPrev(treeId, nodes, targetNode) {
	var pNode = targetNode.getParentNode();
	if (pNode && pNode.dropInner === false) {
		return false;
	} else {
		for (var i=0,l=curDragNodes.length; i<l; i++) {
			var curPNode = curDragNodes[i].getParentNode();
			if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
				return false;
			}
		}
	}
	console.log('dropPrev')
	setTimeout(function(){

	})
	return true;
}
function dropInner(treeId, nodes, targetNode) {
	if (targetNode && targetNode.dropInner === false) {
		return false;
	} else {
		for (var i=0,l=curDragNodes.length; i<l; i++) {
			if (!targetNode && curDragNodes[i].dropRoot === false) {
				return false;
			} else if (curDragNodes[i].parentTId && curDragNodes[i].getParentNode() !== targetNode && curDragNodes[i].getParentNode().childOuter === false) {
				return false;
			}
		}
	}
	console.log('dropPrev...')
	return true;
}

function onDrop(){
	console.log('onDrop')
	setTimeout(function(){
		var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
		var nodes = treeObj.getNodes();
		
		blNameArrays = []
		zlNameArrays = []

		for(var m=0;m<nodes.length;m++){
            var subNodes = nodes[m].children;
            //后台保存格式
            if(m == 0 ){//宾栏
                blNameArrays = nodes[m]
                // console.log(blIncludeArray)
            }else{//主栏
                zlNameArrays = nodes[m]
                // console.log(zlIncludeArray)
            }
        }

        function getTableNodes(nodes){
            var arr = []
            for(var i=0;i<nodes.length;i++){
                var node = nodes[i]
                var tempNode = {
                    'id': node.id,
                    'pId': node.pId,
                    'name': node.name
                }
                if(node.children && node.children.length > 0){
                    var children = []
                    for(var j=0;j<node.children.length;j++){
                        var childNode = {
                            'id': node.children[j].id,
                             'pId': node.children[j].pId,
                             'name': node.children[j].name
                        }
                        if(node.children[j].children && node.children[j].children.length > 0){
                            childNode.children = getTableNodes(node.children[j].children)
                        }
                        children.push(childNode)
                    }
                    tempNode.children = children
                }
                arr.push(tempNode)
            }
            return arr
            
        }
	},50)
}

function dropNext(treeId, nodes, targetNode) {
	var pNode = targetNode.getParentNode();
	if (pNode && pNode.dropInner === false) {
		return false;
	} else {
		for (var i=0,l=curDragNodes.length; i<l; i++) {
			var curPNode = curDragNodes[i].getParentNode();
			if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
				return false;
			}
		}
	}
	return true;
}

function beforeDrag(treeId, treeNode) {
	for(var i=0;i<treeNode.length;i++){
	　　if(treeNode[i].drag == false || !treeNode[i].getParentNode())  
	　　　return false;　　　  
	　}  
	curDragNodes = treeNode;
	　return true;  
}
function beforeDrop(treeId, treeNode, targetNode) {
	//处理拖拽事件  
	if(!targetNode){
		return false
	}
	if(targetNode.id ==1 || targetNode.id ==2){
		return false
	}
	　for(var i = 0;i<treeNode.length;i++){  
	　　var curNode = treeNode[i];  
	　　var pNode = curNode.getParentNode();  
	　　//只允许同级拖拽
		targetNode.getParentNode()
		
		var inZl = [zlNameArrays].find(function(item){
			if(pNode){
				return item.id == pNode.id
			}
			return false
		})
		var inZl2 = [zlNameArrays].find(function(item){
			if(targetNode.getParentNode()){
				return item.id == targetNode.getParentNode().id
			}
			return false
		})

		if((inZl && ! inZl2) || (!inZl && inZl2)){
			return false
		}  
	　}  
}

function showRemoveBtn(treeId, treeNode) {
	return !treeNode.isParent ;
}
function showRenameBtn(treeId, treeNode) {
	if(treeNode.id == 1 || treeNode.id == 2){
		return false
	}
	return true
	return !treeNode.isParent ;
}
var tempIdStart = 1
function getZBResult(node,isEdit,isZhibiao){
	var zbSelect1 = document.getElementById('zb_select_1')
	var zbSelect2 = document.getElementById('zb_select_2')
	var zbSelect3 = document.getElementById('zb_select_3')
	var zbSelect4 = document.getElementById('zb_select_4')
	var zbSelect5 = document.getElementById('zb_select_5')
	var xspc = document.getElementById('xspc')

	var value1 = zbSelect1.selectedOptions[0].getAttribute('value')
	var rnum = zbSelect1.selectedOptions[0].getAttribute('rnum')
	var code = zbSelect1.selectedOptions[0].getAttribute('code')
	var value2 = zbSelect2.selectedOptions[0].getAttribute('value')
	var code2 = zbSelect2.selectedOptions[0].getAttribute('code')
	var value2_1 = zbSelect2.selectedOptions[0].getAttribute('colType')

	var value3 = zbSelect3.selectedOptions[0].getAttribute('value')
	var value3_index = zbSelect3.selectedIndex

	var value4 = zbSelect4.selectedOptions[0].getAttribute('value')
	var value4_index = zbSelect4.selectedIndex

	var value5 = zbSelect5.selectedOptions[0].getAttribute('value')

	

	var value6 = xspc.value

	var calc = null

	

	var tItem = findItem((blNameArrays instanceof Array ? blNameArrays : [blNameArrays]),node.id)
	function findItem(arr,id){
		for(var i=0;i<arr.length;i++){
			if(arr[i].id == id){
				return arr[i]
			}
			if(arr[i].children){
				var item = findItem(arr[i].children,id)
				if(item){
					return item
				}
			}
		}
	}

	if(!isZhibiao){
		calc =  getCalResult()
	}

	if(!isEdit){
		var treeNode = {}
		if(!calc){
			treeNode = {
				'id':100000+tempIdStart++,
				'pId':node.id,
				'name':value6,
				'':"drag:true,drop:true",
				'indexDm':code,
				'indexColumn':code2,
				'starttime':value3_index,
				'endtime':value4_index,
				'display':value5 == '是'?'Y':'N',
				'pxh':'',
				'columnType':value2_1,
				'isNew':true,
				'rnum':rnum,
				calc:calc
			}
		} else {
			treeNode = {
				'id':100000+tempIdStart++,
				'pId':node.id,
				'':"drag:true,drop:true",
				'pxh':'',
				'name':calc.xsmc,
				'express':calc.jsbdas,
				'display':calc.ifshow,
				'tjfw':calc.tjfw,
				'rnum':node.rnum
			}
		}

		if(node.id == 1 || node.id ==2){
			blNameArrays.push(treeNode)
		} else {
			if(tItem){
				if(!tItem.hasOwnProperty('children')){
					tItem.children = []
				}
				tItem.children.push(treeNode)
			}
		}
	} else {
		if(tItem){
			if(calc){
				tItem.name = calc.xsmc
				tItem.express = calc.jsbdas
				tItem.display = calc.ifshow
				tItem.tjfw = calc.tjfw
				tItem.pxh=''

				delete tItem.indexDm
				delete tItem.indexColumn
				delete tItem.starttime
				delete tItem.endtime
				delete tItem.columnType
			} else {
				tItem.name = value6
				tItem.indexDm = code2
				tItem.starttime = value3_index
				tItem.endtime = value4_index
				tItem.columnType = value2_1
			}
			tItem.isNew = true
		}
	}
	flag = 0;
	createTree()
}
var groupStartIndex = `1`
function getFuzuDetail(node,isEdit){
	var select1 = document.getElementById('gp_select_1').selectedOptions[0]

	var select2 = document.getElementById('gp_select_2') ? document.getElementById('gp_select_2').selectedOptions[0] : null
	var cs = document.getElementById('gp_select_2').selectedIndex + 1
	var nameInput = document.getElementById('gxsmc')
	var realName = nameInput.value
	var name = select1.getAttribute('value')
	var column = select1.getAttribute('column')
	var tItem = findItem(zlNameArrays,id)

	function findItem(arr,id){
		for(var i=0;i<arr.length;i++){
			if(arr[i].id == id){
				return arr[i]
			}
			if(arr[i].children){
				var item = findItem(arr[i].children,id)
				if(item){
					return item
				}
			}
		}
	}

	if(!isEdit){
		var treeNode = {
			'id': 20000+groupStartIndex,
			'pId':node.id,
			'name':realName,
			'':"drag:true,drop:true",
			'groupColumn':column,
			'groupAdded':'',
			'pxh':'',
			'groupType':'NORMAL',
			'isNew':true,
			'cs':cs
		}
		groupStartIndex++

		if(node.id == 1 || node.id == 2){
			zlNameArrays.push(treeNode);
		} else {
			if(tItem){
				if(!tItem.hasOwnProperty('children')){
					tItem.children = []
				}
				tItem.children.push(treeNode)
			}
		}
	} else {
		if(tItem){
			tItem[index].groupColumn = column
			tItem[index].name = realName
			tItem[index].cs = cs
		}
	}
	flag = 0
	createTree()
}

function getCalResult(node,isEdit){
	var xsmc = document.getElementById('ggxspc').value
	var jsbdas = document.getElementById('ggjsbdas').value
	var tjfw = document.getElementById('ggtjfw').value
	var ifshow = document.getElementById('ggifshow').selectedOptions[0].getAttribute('value')

	return {
		xsmc:xsmc,
		jsbdas:jsbdas,
		tjfw:tjfw,
		ifshow:ifshow == '是' ? 'Y' :'N'
	}
}

function addHoverDom(treeId, treeNode) {
	var sObj = $("#" + treeNode.tId + "_span");
	if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
	var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
		+ "' title='add node' onfocus='this.blur();'></span>";
	sObj.after(addStr);
	var btn = $("#addBtn_"+treeNode.tId);
	var editBtn = $("#"+treeNode.tId+'_edit')
	var delBtn = $('#'+treeNode.tId+'_remove')
	if(delBtn){
		delBtn.bind("click",function(e){
			totalSaveBtnEnable = true
		})
	}
	if(editBtn){
		editBtn.bind("click",function(e){
			if(treeNode.hasOwnProperty('columnType') || treeNode.hasOwnProperty('tjfw')){
				var rnum = treeNode.rnum ? [treeNode.rnum] : num
				var zDataArr = []
				for(var i =0;i<rnum.length;i++){
					var data = columnList[rnum[i]]
					if(data){
						for(var j=0;j<data.zblist.length;j++){
							var obj = data.zblist[j]
							obj.collist = data.collist
							zDataArr.push(obj)
						}
					}
				}
				zbData = data.collist
				setzhibiaoHtml(null,null,zDataArr,treeNode)
				setjislHtml(treeNode)

				layer.tab({
					area: ['400px', '350px'],
					tab: [{
					title: '指标', 
					content: zhibiaoHtml
					}, {
					title: '计算列', 
					content: jislHtml
					}],
					btn: ['确定','取消'], //按钮,
					yes:function(index){
						var isZhibiao = $('.layui-this')[0].innerHTML == "指标" 
						layer.close(index);
						getZBResult(treeNode,true,isZhibiao)
						totalSaveBtnEnable = true
					},
					btn2:function(){
					}
				});
			} else {
				setGroupHtml(rowList,treeNode,true)
				layer.tab({
					area: ['400px', '350px'],
					tab: [{
					title: '分组', 
					content: groupHtml
					}],
					btn: ['确定','取消'], //按钮,
					yes:function(index){
						layer.close(index);
						getFuzuDetail(treeNode,true)
						totalSaveBtnEnable = true
					},
					btn2:function(){
					}
				});
			}
		})
	}
	if (btn) btn.bind("click", function(){
		if(treeNode.hasOwnProperty('columnType') || treeNode.hasOwnProperty('tjfw') || treeNode.id == 1){//treeNode.pId == 1
			var zbData = null;
			var rnum = treeNode.rnum ? [treeNode.rnum] : num
			var zDataArr = []
			for(var i =0;i<rnum.length;i++){
				var data = columnList[rnum[i]]
				if(data){
					for(var j=0;j<data.zblist.length;j++){
						var obj = data.zblist[j]
						obj.collist = data.collist
						obj.rnum = rnum[i]
						zDataArr.push(obj)
					}
				}
			}
			zbListData = zDataArr
				zbData = data.collist
				setzhibiaoHtml(null,null,zDataArr)
				setjislHtml(treeNode)

				layer.tab({
					area: ['500px', '350px'],
					tab: [{
					title: '指标', 
					content: zhibiaoHtml
					}, {
					title: '计算列', 
					content: jislHtml
					}],
					btn: ['确定','取消'], //按钮,
					yes:function(index){
						var isZhibiao = $('.layui-this')[0].innerHTML == "指标" 
						layer.close(index);
						getZBResult(treeNode,false,isZhibiao)
						totalSaveBtnEnable = true
					},
					btn2:function(){
					}
				});
		} else if(treeNode.pId == 2 || treeNode.id == 2){
			setGroupHtml(rowList,treeNode,false)
			layer.tab({
				area: ['400px', '350px'],
				tab: [{
				title: '分组', 
				content: groupHtml
				}],
				btn: ['确定','取消'], //按钮,
				yes:function(index){
					layer.close(index);
					getFuzuDetail(treeNode,false)
					totalSaveBtnEnable = true
					

				},
				btn2:function(){
				}
			});
		}
	});
};
function removeHoverDom(treeId, treeNode) {
	$("#addBtn_"+treeNode.tId).unbind().remove();

};

